/*
 * Copyright 2019 The nity.io gRPC Spring Boot Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.nity.grpc.sample.grpc;

import io.grpc.ManagedChannelBuilder;
import io.nity.grpc.client.channel.configurer.GrpcChannelBuilderConfigurer;
import io.nity.grpc.client.channel.configurer.GrpcChannelConfigurer;
import io.nity.grpc.client.channel.factory.CustomChannelFactory;
import io.nity.grpc.client.config.GrpcClientProperties;
import io.nity.grpc.client.config.GrpcClientPropertiesMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class GrpcClientConfig {

    @Autowired
    protected GrpcClientPropertiesMap clientPropertiesMap;

    /**
     * custom模式下ChannelBuilder自定义
     */
    @Bean
    public CustomChannelFactory customChannelFactory(final GrpcClientPropertiesMap clientPropertiesMap,
                                                     final GrpcChannelBuilderConfigurer channelBuilderConfigurer,
                                                     final GrpcChannelConfigurer channelConfigurer) {
        return new CustomChannelFactory(clientPropertiesMap, channelBuilderConfigurer, channelConfigurer) {
            @Override
            protected ManagedChannelBuilder newChannelBuilder(final String name, final GrpcClientProperties clientProperties) {
                String host = clientProperties.getHost();
                int port = clientProperties.getPort();

                ManagedChannelBuilder<?> managedChannelBuilder = ManagedChannelBuilder.forAddress(host, port).usePlaintext();
                return managedChannelBuilder;
            }
        };
    }

    /**
     * ChannelBuilder配置器，在builder.build()前调用
     * 适用所有模式
     */
    @Bean
    public GrpcChannelBuilderConfigurer channelBuilderConfigurer() {
        return (channelBuilder, name) -> {
            log.info("configure channelBuilder...");
            //channelBuilder.loadBalancerFactory(something);
            //etc.
        };
    }

    /**
     * Channel配置器，在channel创建后调用
     * 适用所有模式
     */
    @Bean
    public GrpcChannelConfigurer channelConfigurer() {
        return (channel, name) -> {
            log.info("configure channel...");
            //ClientInterceptors.intercept(channel, interceptors);
            //etc.
        };
    }
}
